package model

import (
	"autoclave/global"
	"context"
	"fmt"
	"github.com/mojocn/base64Captcha"
	"image/color"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct{}

// var store = base64Captcha.DefaultMemStore
var store base64Captcha.Store = RedisStore{}

var ctx = context.Background()

// GenerateCaptcha 生成验证码
func GenerateCaptcha() (string, string, string, error) {
	var driver base64Captcha.Driver
	driverString := base64Captcha.DriverString{
		Height:          120,
		Width:           300,
		NoiseCount:      0,
		ShowLineOptions: 2 | 4,
		Length:          4,
		Source:          "1234567890qwertyuiopasdfghjklzxcvbnm",
		BgColor: &color.RGBA{
			R: 103,
			G: 102,
			B: 214,
			A: 125,
		},
		Fonts: []string{"wqy-microhei.ttc"},
	}
	driver = driverString.ConvertFonts()
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, answer, err := c.Generate()
	return id, b64s, answer, err
}

// VerifyCaptcha 验证
func VerifyCaptcha(id string, value string) bool {
	if id == "" || value == "" {
		return false
	}
	if store.Verify(id, value, true) {
		return true
	} else {
		return false
	}
}

// Set 实现设置captcha的方法
func (r RedisStore) Set(id string, value string) error {
	key := CAPTCHA + id
	err := global.RedisDb.Set(ctx, key, value, time.Minute*2).Err()
	return err
}

// Get 实现获取captcha的方法
func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	val, err := global.RedisDb.Get(ctx, key).Result()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	if clear {
		err = global.RedisDb.Del(ctx, key).Err()
		if err != nil {
			fmt.Println(err)
			return ""
		}
	}
	return val
}

// Verify 实现验证captcha的方法
func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := RedisStore{}.Get(id, clear)
	//fmt.Println("key:"+id+";value:"+v+";answer:"+answer)
	//if v == answer {
	//	_ = global.RedisDb.Del(ctx, CAPTCHA + id).Err()
	//}
	return v == answer
}
